import React, { useState, useEffect } from 'react';
import { Button, Card, Layout, Menu, Typography, Space, Row, Col, Statistic, message, Tag } from 'antd';
import { 
  MenuFoldOutlined, 
  MenuUnfoldOutlined, 
  DashboardOutlined, 
  LineChartOutlined, 
  UserOutlined,
  StockOutlined,
  SettingOutlined,
  DatabaseOutlined,
  ApiOutlined,
  BarChartOutlined,
  PieChartOutlined
} from '@ant-design/icons';
import StockList from './components/StockList';
import StockDetail from './components/StockDetail';
import StockCharts from './components/StockCharts';
import Stock3DChart from './components/Stock3DChart';
import { stockApi } from './services/stockApi';
import './App.css';

const { Header, Sider, Content } = Layout;
const { Title } = Typography;

function App() {
  const [collapsed, setCollapsed] = useState(false);
  const [currentView, setCurrentView] = useState('dashboard');
  const [selectedStock, setSelectedStock] = useState(null);
  const [serviceStatus, setServiceStatus] = useState('unknown');

  // 检查后端服务状态
  const checkServiceStatus = async () => {
    try {
      const status = await stockApi.healthCheck();
      setServiceStatus(status.status);
      message.success('后端服务连接正常');
    } catch (error) {
      setServiceStatus('unhealthy');
      message.error('后端服务连接失败，请确保后端服务已启动');
    }
  };

  // 查看股票详情
  const handleViewStock = (stock) => {
    setSelectedStock(stock);
    setCurrentView('stockDetail');
  };

  // 返回股票列表
  const handleBackToList = () => {
    setSelectedStock(null);
    setCurrentView('stockList');
  };

  // 返回仪表盘
  const handleBackToDashboard = () => {
    setSelectedStock(null);
    setCurrentView('dashboard');
  };

  // 菜单点击处理
  const handleMenuClick = ({ key }) => {
    switch (key) {
      case '1':
        setCurrentView('dashboard');
        break;
      case '2':
        setCurrentView('stockList');
        break;
      case '3':
        setCurrentView('stockCharts');
        break;
      case '3d':
        setCurrentView('stock3DChart');
        break;
      case '4':
        message.info('投资组合功能开发中...');
        break;
      case '5':
        message.info('个人中心功能开发中...');
        break;
      case '6':
        message.info('系统设置功能开发中...');
        break;
      default:
        break;
    }
  };

  // 组件挂载时检查服务状态
  useEffect(() => {
    checkServiceStatus();
  }, []);

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo" style={{ 
          height: 32, 
          margin: 16, 
          background: 'rgba(255, 255, 255, 0.3)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: 'white',
          fontWeight: 'bold'
        }}>
          {collapsed ? 'S' : 'Stock Study'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['1']}
          selectedKeys={[
            currentView === 'dashboard' ? '1' : 
            currentView === 'stockList' ? '2' : 
            currentView === 'stockCharts' ? '3' : 
            currentView === 'stock3DChart' ? '3d' : '1'
          ]}
          onClick={handleMenuClick}
          items={[
            {
              key: '1',
              icon: <DashboardOutlined />,
              label: '仪表盘',
            },
            {
              key: '2',
              icon: <LineChartOutlined />,
              label: '股票列表',
            },
            {
              key: '3',
              icon: <BarChartOutlined />,
              label: '数据分析图表',
            },
            {
              key: '3d',
              icon: <PieChartOutlined />,
              label: '三维图表',
            },
            {
              key: '4',
              icon: <StockOutlined />,
              label: '投资组合',
            },
            {
              key: '5',
              icon: <UserOutlined />,
              label: '个人中心',
            },
            {
              key: '6',
              icon: <SettingOutlined />,
              label: '系统设置',
            },
          ]}
        />
      </Sider>
      <Layout>
        <Header style={{ 
          padding: 0, 
          background: '#fff',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between'
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              style={{
                fontSize: '16px',
                width: 64,
                height: 64,
              }}
            />
            <Title level={3} style={{ margin: 0, marginLeft: 16 }}>
              股票研究前端系统
            </Title>
          </div>
          <div style={{ paddingRight: 24, display: 'flex', alignItems: 'center' }}>
            <Space style={{ marginRight: 16 }}>
              <Tag icon={<ApiOutlined />} color="geekblue">
                开发环境
              </Tag>
              <Tag color="blue">http://localhost:8080</Tag>
            </Space>
            <span style={{ marginRight: 16 }}>
              当前页面: {currentView === 'dashboard' ? '仪表盘' : 
                       currentView === 'stockList' ? '股票列表' : 
                       currentView === 'stockDetail' ? '股票详情' : 
                       currentView === 'stockCharts' ? '数据分析图表' : 
                       currentView === 'stock3DChart' ? '三维图表' : '未知'}
            </span>
            {(currentView === 'stockList' || currentView === 'stockDetail' || currentView === 'stockCharts' || currentView === 'stock3DChart') && (
              <Button onClick={handleBackToDashboard} size="small">
                返回首页
              </Button>
            )}
          </div>
        </Header>
        <Content style={{ 
          margin: '24px 16px', 
          padding: 24, 
          background: '#fff',
          borderRadius: 8
        }}>
          {(() => {
            switch (currentView) {
              case 'stockList':
                return (
                  <StockList 
                    onViewStock={handleViewStock}
                    onBack={handleBackToDashboard}
                  />
                );
              case 'stockDetail':
                return (
                  <StockDetail 
                    stock={selectedStock}
                    onBack={handleBackToList}
                  />
                );
              case 'stockCharts':
                return (
                  <StockCharts 
                    onBack={handleBackToDashboard}
                  />
                );
              case 'stock3DChart':
                return (
                  <Stock3DChart 
                    onBack={handleBackToDashboard}
                  />
                );
              case 'dashboard':
              default:
                return (
                  <Space direction="vertical" size="large" style={{ width: '100%' }}>
                    <div>
                      <h1>股票研究系统</h1>
                      <p>欢迎使用股票研究系统，这里可以查看股票数据和分析结果。</p>
                       
                      {/* 服务状态指示器 */}
                      <Space style={{ marginBottom: 16 }}>
                        <span>后端服务状态:</span>
                        <Button 
                          type="text" 
                          icon={<DatabaseOutlined />}
                          onClick={checkServiceStatus}
                          style={{ 
                            color: serviceStatus === 'healthy' ? '#52c41a' : 
                                   serviceStatus === 'unhealthy' ? '#ff4d4f' : '#faad14'
                          }}
                        >
                          {serviceStatus === 'healthy' ? '正常' : 
                           serviceStatus === 'unhealthy' ? '异常' : '检查中...'}
                        </Button>
                      </Space>
                    </div>
                     
                    <Row gutter={16}>
                      <Col xs={24} sm={12} md={6}>
                        <Card>
                          <Statistic title="总股票数" value={1128} prefix={<StockOutlined />} />
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card>
                          <Statistic title="今日涨幅" value={9.3} suffix="%" precision={2} valueStyle={{ color: '#3f8600' }} />
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card>
                          <Statistic title="今日跌幅" value={2.1} suffix="%" precision={2} valueStyle={{ color: '#cf1322' }} />
                        </Card>
                      </Col>
                      <Col xs={24} sm={12} md={6}>
                        <Card>
                          <Statistic title="成交金额" value={112893} suffix="亿" />
                        </Card>
                      </Col>
                    </Row>
                     
                    <Card title="快速操作" variant="borderless">
                      <Space wrap>
                        <Button 
                          type="primary" 
                          icon={<LineChartOutlined />}
                          onClick={() => setCurrentView('stockList')}
                        >
                          查看股票列表
                        </Button>
                        <Button 
                          type="default" 
                          icon={<BarChartOutlined />}
                          onClick={() => setCurrentView('stockCharts')}
                        >
                          数据分析图表
                        </Button>
                        <Button 
                          type="default" 
                          icon={<PieChartOutlined />}
                          onClick={() => setCurrentView('stock3DChart')}
                        >
                          三维图表
                        </Button>
                        <Button icon={<StockOutlined />}>添加自选股</Button>
                        <Button icon={<DashboardOutlined />}>市场分析</Button>
                        <Button icon={<SettingOutlined />}>系统设置</Button>
                      </Space>
                    </Card>
                     
                    <Card title="功能说明">
                      <Row gutter={[16, 16]}>
                        <Col xs={24} md={8}>
                          <h3>📊 股票列表功能</h3>
                          <ul>
                            <li>查看所有股票的基本信息</li>
                            <li>支持按股票代码搜索</li>
                            <li>支持按价格、涨跌幅排序</li>
                            <li>点击"查看详情"查看完整信息</li>
                          </ul>
                        </Col>
                        <Col xs={24} md={8}>
                          <h3>🔍 股票详情功能</h3>
                          <ul>
                            <li>查看股票的完整详细信息</li>
                            <li>价格走势和涨跌幅分析</li>
                            <li>股本结构和股息信息</li>
                            <li>技术指标和统计数据</li>
                          </ul>
                        </Col>
                        <Col xs={24} md={8}>
                          <h3>📈 数据分析图表</h3>
                          <ul>
                            <li>股息与最高价关系图</li>
                            <li>流通量与最高价关系图</li>
                            <li>可视化数据分析</li>
                            <li>交互式图表展示</li>
                          </ul>
                        </Col>
                        <Col xs={24} md={8}>
                          <h3>🎯 三维图表</h3>
                          <ul>
                            <li>流通量、分红、最高价三维关系图</li>
                            <li>交互式三维可视化</li>
                            <li>支持自动旋转和缩放</li>
                            <li>鼠标悬停查看详细信息</li>
                          </ul>
                        </Col>
                      </Row>
                    </Card>
                  </Space>
                );
            }
          })()}
        </Content>
      </Layout>
    </Layout>
  );
}

export default App;